#pragma once

#include <iostream>
#include <string>
#include <functional>
#include <cerrno>
#include <cstring>
#include <unistd.h>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "nocopy.hpp"
#include "Log.hpp"
#include "Comm.hpp"
#include "InetAddr.hpp"
using namespace std;

const static std::string defaultip = "0.0.0.0";
const static uint16_t defaultport = 8888;
const static int defaultfd = -1;
const static int defaultsize = 1024;

using func_t = std::function<const string(string)>;// 定义一个函数类型

//聚焦在IO上
class UdpServer : public nocopy
{
public:
    UdpServer(func_t OnMessage, uint16_t port = defaultport)
    :_port(port),_sockfd(defaultfd),_OnMessage(OnMessage)
    {
    }
    ~UdpServer()
    {
    }
    void Init()
    {
        // 1.创建socket，就是创建文件细节
        // udp是全双工的，既可以读也可以写，可以同时读写，不会有多线程读写的问题
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if(_sockfd < 0)
        {
            lg.LogMessage(Fatal, "socket error, %d : %s\n", errno, strerror(errno));
            exit(Socket_Err);
        }
        lg.LogMessage(Info, "socket success, sockfd: %d\n", _sockfd);
        //2. 绑定,指定网络信息
        struct sockaddr_in local;
        bzero(&local, sizeof(local));// 置0
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);// 主机字节序转网络字节序
        //local.sin_addr.s_addr = inet_addr(_ip.c_str());// 4字节转网络序列
        //不推荐绑定iP
        local.sin_addr.s_addr = INADDR_ANY;//绑定到本机所有网卡的所有 IPv4 地址上,实现动态绑定

        int n = ::bind(_sockfd, (struct sockaddr*)&local, sizeof(local));
        if(n != 0)
        {
            lg.LogMessage(Fatal, "bind error, %d : %s\n", errno, strerror(errno));
            exit(Bind_Err);
        }

    }
    void Start()
    {
        // 服务器永远不退出
        char buffer[defaultsize];//用于存放接收到的数据
        for(;;)
        {
            struct sockaddr_in peer;//用来保存客户端的 IP 地址 和 端口号
            socklen_t len = sizeof(peer);
            ssize_t n = recvfrom(_sockfd, buffer, sizeof(buffer)-1, 0, (struct sockaddr*)&peer, &len);
            if(n > 0)
            {
                InetAddr addr(peer);
                buffer[n] = 0;

                //处理消息
                string response = _OnMessage(buffer);

                //cout << "[" <<addr.PrintDebug() << "]#" << buffer << endl;
                sendto(_sockfd, response.c_str(), response.size(), 0, (struct sockaddr*)&peer, len);
            }
        }
    }
private:
    //std::string _ip;
    uint16_t _port;// 端口号
    int _sockfd; //套接字文件描述符

    func_t _OnMessage;// 回调
};